package xyz.jcat.biz.admin.auth;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import xyz.jcat.biz.admin.domain.po.UserPo;
import xyz.jcat.biz.admin.service.IUserRoleService;
import xyz.jcat.biz.admin.service.IUserService;
import xyz.jcat.web.security.UserDetailsImpl;

import java.util.List;
import java.util.Objects;

@Component
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private IUserService userService;
    @Autowired
    private IUserRoleService userRoleService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserPo user = userService.getByUsername(username);
        UserDetailsImpl userDetails = null;
        if(!Objects.isNull(user)) {
            List<Long> roleIds = userRoleService.getRoleIdsByUserId(user.getId());
            userDetails = new UserDetailsImpl(user.getId(), username, user.getPassword(), roleIds);
        }
        return userDetails;
    }

}
